<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="css/nv.d3.css">
	<script type="text/javascript" src="js/d3.js"></script>
	<script type="text/javascript" src="js/d3.tip.js"></script>
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	<script type="text/javascript" src="js/nv.d3.js"></script>
	<script src="js/dojo-release-1.9.3/dojo/dojo.js"></script>
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dojo/resources/dojo.css">
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dijit/themes/claro/claro.css">
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dojox/grid/resources/claroGrid.css">
	
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style>

.bar {
  fill: steelblue;
}

.bar2 {
  fill: orange;
}

.bar:hover {
  fill: brown;
}

.bar2:hover {
  fill: brown;
}


.axis {
  /*font: 10px sans-serif;*/
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.d3-tip {
  line-height: 1;
  /*font-weight: bold;*/
  padding: 12px;
  background: rgba(0, 0, 0, 0.4);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  /*font-size: 10px;*/
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.4);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
.detailbox {
 font-family: Tahoma,sans-serif;
}

#detail1{
	width : 700px;
	height: 400px;
}

#test{
 	width: 900px ;
	margin-left: auto ;
	margin-right: auto ;
}

#sortMenu{
	border: 2px solid #a1a1a1;
	padding: 2px 2px;
    border-radius: 25px;
}

body{
 font-size:15px;
 font-family: Tahoma,sans-serif;
 color:black;
}

</style>

</head>
<body class="claro">
	<div style="font-size:20px;width:400px;margin-left:auto;margin-right:auto;">รายงานบุคลากร แยกตามคณะ</div>
	<div style="width:1000px;height:330px;margin-left:auto;margin-right:auto;">
		<div style="display:inline-block;margin-left:5px;vertical-align:top;">
			<a href="index.html"><img src="images/home_icon.png"  width="50" height="50"></a>
		</div>
		<div style="display:inline-block;">
			<div id="grid" style="display:inline-block;"></div>
		</div>
	</div>
	<div id="test">
		<div id="sortMenu" style="width:450px;display:inline-block;float:left;">
			<span>เรียงลำดับโดย</span>
		    <input type="radio" name="sort" value="total" id="radio"> จำนวนบุคลากรทั้งหมด
		    <input type="radio" name="sort" value="male" id="radio"> บุคลากรชาย
		    <input type="radio" name="sort" value="female" id="radio">บุคลากรหญิง
		</div>
		<div style="display:inline-block;float:right;">
			<div style="background-color:steelblue;width:20px;height:20px;display:inline-block;"></div>
			<div style="display:inline-block;">ชาย</div>
			<div style="background-color:orange;width:20px;height:20px;display:inline-block;"></div>
			<div style="display:inline-block;">หญิง</div>
		</div>
		<div style="clear:both;"></div>
	</div>
</body>

	<script type="text/javascript">
	
	function genDonutChart(detailDatum){
		//create donutchart
		var donutChartSvg = d3.select("body").append("div").attr("id","detailChart").append("svg").attr("id","donutChart").attr("width","100%").attr("height","300px");
		
		nv.addGraph(function() {
		      var chart = nv.models.pieChart()
		          .x(function(d) { return d.label })
		          .y(function(d) { return d.value })
		          .showLabels(true)     //Display pie labels
		          .labelThreshold(.05)  //Configure the minimum slice size for labels to show up
		          .labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
		          .donut(true)          //Turn on Donut mode. Makes pie chart look tasty!
		          .donutRatio(0.35);     //Configure how big you want the donut hole size to be.
		          

		        d3.selectAll("#donutChart")
		            .datum(detailDatum)
		            .transition().duration(350)
		            .call(chart);

		      return chart;
		}); 
	}
	
	function genDetailContent(detailData){
		
		//var detailTableDiv = detailDiv.append("div")
		//.append("strong").text("รายชื่อบุคลากร");
		require([
					"dojox/grid/DataGrid",
					"dojo/store/Memory",
					"dojo/data/ObjectStore",
					"dojo/request",
					"dijit/Dialog",
					"dojo/dom-construct",
					"dojo/domReady!"
				], function(DataGrid, Memory, ObjectStore, request,Dialog,domConstruct){
						var dialog = dijit.byId('dialog');
						if(!dialog){
							dialog = new Dialog({
						      id:'dialog',
						      //title:'รายชื่อบุคลากร',
						      onCancel: function(){
							    	  if(dojo.byId("detailChart")){
							    	  	dojo.byId("detailChart").remove();
							    	  }
						    	  },
						      style:'width:700px; height:auto;'
						    }); 
						}
						dialog.set("title",detailData[0].name);
						dialog.show();
						
						var grid = dijit.byId('dialogGrid')
						
						var dataStore =  new ObjectStore({ objectStore:new Memory({ data: detailData[1]}) });
						if(!grid){
							grid = new DataGrid({
							id:"dialogGrid",
							query: { id: "*" },
							structure: [
								{ name: "ลำดับ", field: "sequence", width: "50px" },
								{ name: "ชื่อ", field: "name", width: "300px" },
								{ name: "ตำแหน่งทางวิชาการ", field: "acadPosType", width: "100px" },
								{ name: "ระดับปริญญา", field: "degree", width: "100px" },
								{ name: "วิชาเอก", field: "major", width: "100px" },
								{ name: "มหาวิทยาลัย", field: "universityAndCountry", width: "150px" }
							],
							style:'width:680px;height:400px;'
							});
						}
					 var donutChart = dojo.byId("detailChart");
					 
					 if(donutChart){
						 domConstruct.place(donutChart, dialog.containerNode);
						 domConstruct.place(grid.domNode, donutChart,'after');
					 }else{
						 domConstruct.place(grid.domNode, dialog.containerNode,'first');
					 }
					 grid.setStore(dataStore);
					 grid.startup();
				});
	}
	
	function drilldown(p1,p2){
		d3.json("FrmShowStaffAcadByFac?criteria=depId&p1="+p1+"&p2="+p2,function(error,data){
			//var detailDiv = d3.select("body").append("div").attr("class","claro").attr("id","detail1");
			genDonutChart(data[2]);//data[0] is a data for gennerate grid
			genDetailContent(data);//data[1] is a data for gennerate donut chart
			/* $('#detail1').w2popup({width: '700',height:'400',showMax:'true',
									onClose: function () {d3.selectAll('#detail1').remove()},
									onOpen: function(){d3.selectAll('#detail1').style("visibility","hidden");}
			}); */
		});
	}
	
	function drilldownBySex(p1,p2){
		
		d3.json("FrmShowStaffAcadByFac?criteria=depId&p1="+p1+"&p2="+p2,function(error,data){
			//var detailDiv = d3.select("body").append("div").attr("class","claro").attr("id","detail1");
			//var grid = genDetailContent(data,detailDiv);
			genDetailContent(data);
		});
	}//end drilldownBySex
	  
	/* function filterData(origData,filterIndexes){
		var newArray = origData;
		var removedCount = 0;
		for (var i = 0; i<filterIndexes.length; i++){
			newArray.splice(filterIndexes[i]-removedCount,1);
			removedCount++;
		}
		return newArray;
	} */
	
	var margin = {top: 20, right: 50, bottom: 135, left: 60},
    width = 800 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom; 
	var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);
	
	var tip = d3.tip()
	  .attr('class', 'd3-tip')
	  .offset([-10, 0])
	  .html(function(d) {
	    return d.facultyName+" ชาย : <span style='color:red'>" + d.maleStaffAmount + "</span>";
	  });
	
	var tip2 = d3.tip()
	  .attr('class', 'd3-tip')
	  .offset([-10, 0])
	  .html(function(d) {
	    return d.facultyName+" หญิง: <span style='color:red'>" + d.femaleStaffAmount + "</span>";
	  });
	
	d3.json("FrmShowStaffAcadByFac",function(error,jsonData){
		
		//Create Table d3
		/*var table = d3.select("#test2")
	    .append("table")
	    .style("border-collapse", "collapse")
	    .style("border", "2px black solid")

	    var tHead = table.append("thead");
		tHead.append("tr")
		.selectAll("th")
		.data(filterData(d3.values(jsonData[0]),[6]))
		.enter()
		.append("th")
		.style("border", "1px black solid")
	    .style("padding", "5px")
		.text(function(d){return d});
		
	    var tBody = table.append("tbody").selectAll("tr")
	    .data(jsonData[1])
	    .enter().append("tr")
	    .on("mouseover", function(){d3.select(this).style("background-color", "aliceblue")})
	    .on("mouseout", function(){d3.select(this).style("background-color", "white")})
	    .on("click",function(d) {drilldown(d.facultyId,"facDetail")})

	    .selectAll("td")
	    .data(function(d){return filterData( d3.values(d),[6] )})
	    .enter().append("td")
	    .style("border", "1px black solid")
	    .style("padding", "5px")
	    .text(function(d){return d;})
	    .style("font-size", "20px"); */
	    
	     require([
					"dojox/grid/DataGrid",
					"dojo/store/Memory",
					"dojo/data/ObjectStore",
					"dojo/request",
					"dojo/domReady!"
				], function(DataGrid, Memory, ObjectStore, request){
					var	dataStore =  new ObjectStore({ objectStore:new Memory({ data: jsonData[0]}) });
					var	grid = new DataGrid({
							store: dataStore,
							query: { id: "*" },
							structure: [
								{ name: "ลำดับ", field: "sequence", width: "5%" },
								{ name: "คณะ", field: "facultyName", width: "30%" },
								{ name: "ชาย", field: "maleStaffAmount", width: "7%" },
								{ name: "หญิง", field: "femaleStaffAmount", width: "7%" },
								{ name: "รวม(คน)", field: "totalStaff", width: "10%" },
								{ name: "เปอร์เซ็นต์", field: "percentage", width: "15%" ,formatter: function(percenttage){return percenttage+"%";}}
							],
							style:'width:900px; height:320px;'
						}, "grid");
						grid.startup();
						
						var idx,itm,value;
						dojo.connect(grid, "onRowClick", grid, function(evt){
							idx = evt.rowIndex;
							item = this.getItem(idx);
							value = this.store.getValue(item,"facultyId");
							drilldown(value,"facDetail");
						});
				});
	    
		
		var y = d3.scale.linear().range([height, 0]);
		
		var xAxis = d3.svg.axis()
		    .scale(x)
		    .orient("bottom");
	
		var yAxis = d3.svg.axis()
		    .scale(y)
		    .orient("left")
		    .ticks(10);
		
		var svg = d3.select("#test").append("svg")
		    .attr("width", width + margin.left + margin.right)
		    .attr("height", height + margin.top + margin.bottom)
		    .append("g")
		    .attr("class","graph")
		    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
		
		svg.call(tip);
		svg.call(tip2);

	  x.domain(jsonData[0].map(function(d) { return d.facultyName; }));
	  y.domain([0, d3.max(jsonData[0]
	  , function(d) { 
		  if(d.maleStaffAmount > d.femaleStaffAmount){
			  return d.maleStaffAmount; 
		  }
		  else{
			  return d.femaleStaffAmount
		  }
	  })]);

	  svg.append("g")
	      .attr("class", "x axis")
	      .attr("transform", "translate(0," + height + ")")
	      .call(xAxis)
	      .selectAll("text")
	      .style("text-anchor","end")
	      .attr("transform",function(d){
	    	  return "translate(" +  this.getBBox().height + "," +
	    			  this.getBBox().height + ")rotate(-45)";
	      });

	  svg.append("g")
	      .attr("class", "y axis")
	      .attr("transform", "rotate(0)")
	      .call(yAxis)
	      .append("text")
	      .attr("y", -10)
	      .attr("dy", ".71em")
	      .style("text-anchor", "end")
	      .text("Amount");
	  
	  
	  bars = svg.selectAll(".bar").data(jsonData[0]).enter();
	  
	  bars.append("rect")
	      .attr("class", "bar")
	      .attr("x", function(d) { return x(d.facultyName); })
	      .attr("width", x.rangeBand()/2)
	      .attr("y", function(d) { return y(d.maleStaffAmount); })
	      .attr("height", function(d) { return height - y(d.maleStaffAmount); })
	      .on('mouseover',tip.show)
	      .on('mouseout',tip.hide)
	  	  .on("click",function(d) {drilldownBySex(d.facultyId,"male")});
	      
	  bars.append("rect")
	      .attr("class", "bar2")
	      .attr("x", function(d) { return x(d.facultyName) + x.rangeBand()/2; })
	      .attr("width", x.rangeBand()/2)
	      .attr("y", function(d) { return y(d.femaleStaffAmount); })
	      .attr("height", function(d) { 
	    	  return height - y(d.femaleStaffAmount); })
	      .on('mouseover',tip2.show)
	      .on('mouseout',tip2.hide)
	  	  .on("click",function(d) { drilldownBySex(d.facultyId,"female")});
	   	
	  d3.selectAll("#radio").on("change",function(){
		  change(this.value);
	  });
		
		function change(sortType) {
		    //clearTimeout(sortTimeout);

		    // Copy-on-write since tweens are evaluated after a delay.
		    var x0;
		    if(sortType=="total"){
			    x0 = x.domain(jsonData[0].sort( function(a, b) { return b.totalStaff - a.totalStaff; })
		        .map(function(d) { return d.facultyName; }))
		        .copy();
		    }
		    
		    else if(sortType=="male"){
			    x0 = x.domain(jsonData[0].sort( function(a, b) { return b.maleStaffAmount - a.maleStaffAmount; })
		        .map(function(d) { return d.facultyName; }))
		        .copy();
		    }
		    
		    else if(sortType=="female"){
			    x0 = x.domain(jsonData[0].sort( function(a, b) { return b.femaleStaffAmount - a.femaleStaffAmount; })
		        .map(function(d) { return d.facultyName; }))
		        .copy();
		    }
		    graphTransition(x0);
		    
		   function graphTransition(newX){

		    var transition = svg.transition().duration(750),
		        delay = function(d, i) { return i * 50; };

		    transition.selectAll(".bar")
		        .delay(delay)
		        .attr("x", function(d) { return newX(d.facultyName); });
		    
		    transition.selectAll(".bar2")
	        .delay(delay)
	        .attr("x", function(d) { return newX(d.facultyName)+ newX.rangeBand()/2; });

		    transition.select(".x.axis")
		        .call(xAxis)
		        .selectAll("g")
		        
		        .selectAll("text")
		        .style("text-anchor","end")
		        .attr("transform",function(d){
	    	  			return "translate(" +  this.getBBox().height + "," +
	    			  	this.getBBox().height + ")rotate(-45)";
	      		})
		        .delay(delay);
		    }
		}//end change
	});
	
	</script>
</html>